function dataURItoBlob(dataURI, type) {
  var binary = atob(dataURI.split(',')[1])
  var array = []
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i))
  }
  return new Blob([new Uint8Array(array)], { type: type })
}
export default file => {
  const imgQuality = 0.5 // 压缩图片的质量
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    const image = new Image()
    image.onload = () => {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      const width = image.width * imgQuality
      const height = image.height * imgQuality
      canvas.width = width
      canvas.height = height
      context.clearRect(0, 0, width, height)
      context.drawImage(image, 0, 0, width, height)
      const dataUrl = canvas.toDataURL(file.type)
      const blobData = dataURItoBlob(dataUrl, file.type)
      if (blobData.size < 1024 * 1024 * 10) {
        resolve(blobData)
      } else {
        reject('抱歉,上传的图片大小过大')
      }
    }
    reader.onload = e => {
      image.src = e.target.result
    }
    reader.readAsDataURL(file)
  })
}
